/**
 * AI工作管理器
 * 管理Web Worker池，优化AI计算性能
 */

class AIWorkManager {
    constructor() {
        this.workers = [];
        this.workerCount = Math.min(4, navigator.hardwareConcurrency || 2);
        this.taskQueue = [];
        this.pendingTasks = new Map();
        this.taskId = 0;
        this.initialized = false;
        
        this.initWorkers();
    }

    initWorkers() {
        console.log(`🔧 初始化${this.workerCount}个AI Worker...`);
        
        for (let i = 0; i < this.workerCount; i++) {
            try {
                const worker = new Worker('./js/workers/aiWorker.js');
                worker.onmessage = (e) => this.handleWorkerMessage(e);
                worker.onerror = (error) => {
                    console.error(`Worker ${i} 错误:`, error);
                };
                
                this.workers.push({
                    worker,
                    busy: false,
                    id: i
                });
                
                console.log(`✅ Worker ${i} 初始化完成`);
            } catch (error) {
                console.warn(`⚠️ Worker ${i} 初始化失败，回退到同步模式:`, error);
                this.workers.push({
                    worker: null,
                    busy: false,
                    id: i,
                    fallback: true
                });
            }
        }
        
        this.initialized = true;
    }

    handleWorkerMessage(e) {
        const { type, id, data, error } = e.data;
        
        if (error) {
            console.error('Worker错误:', error);
            this.rejectTask(id, error);
            return;
        }
        
        const task = this.pendingTasks.get(id);
        if (!task) return;
        
        this.pendingTasks.delete(id);
        
        // 释放Worker
        const workerInfo = this.workers.find(w => w.worker === e.target);
        if (workerInfo) {
            workerInfo.busy = false;
        }
        
        // 解析任务
        task.resolve(data);
        
        // 处理队列中的下一个任务
        this.processNextTask();
    }

    getAvailableWorker() {
        return this.workers.find(w => !w.busy && w.worker);
    }

    async postTask(type, data, priority = 0) {
        return new Promise((resolve, reject) => {
            const taskId = ++this.taskId;
            const task = {
                id: taskId,
                type,
                data,
                priority,
                resolve,
                reject,
                timestamp: Date.now()
            };
            
            this.pendingTasks.set(taskId, task);
            
            const worker = this.getAvailableWorker();
            if (worker) {
                this.executeTask(worker, task);
            } else {
                // 根据优先级插入队列
                const insertIndex = this.taskQueue.findIndex(t => t.priority < priority);
                if (insertIndex === -1) {
                    this.taskQueue.push(task);
                } else {
                    this.taskQueue.splice(insertIndex, 0, task);
                }
                
                // 如果队列太长，执行同步回退
                if (this.taskQueue.length > 20) {
                    this.executeFallbackTask(task);
                }
            }
        });
    }

    executeTask(workerInfo, task) {
        workerInfo.busy = true;
        workerInfo.worker.postMessage({
            type: task.type,
            id: task.id,
            data: task.data
        });
    }

    processNextTask() {
        if (this.taskQueue.length === 0) return;
        
        const worker = this.getAvailableWorker();
        if (!worker) return;
        
        const task = this.taskQueue.shift();
        this.executeTask(worker, task);
    }

    executeFallbackTask(task) {
        // 同步回退执行
        setTimeout(() => {
            try {
                let result;
                switch (task.type) {
                    case 'findPath':
                        result = this.fallbackFindPath(task.data);
                        break;
                    case 'analyzePlayerBehavior':
                        result = this.fallbackAnalyzePlayerBehavior(task.data);
                        break;
                    case 'calculateOptimalStrategy':
                        result = this.fallbackCalculateOptimalStrategy(task.data);
                        break;
                    default:
                        throw new Error('Unknown task type: ' + task.type);
                }
                
                this.pendingTasks.delete(task.id);
                task.resolve(result);
            } catch (error) {
                this.rejectTask(task.id, error.message);
            }
        }, 0);
    }

    rejectTask(taskId, error) {
        const task = this.pendingTasks.get(taskId);
        if (task) {
            this.pendingTasks.delete(taskId);
            task.reject(error);
        }
    }

    // 回退实现
    fallbackFindPath(data) {
        // 简化的同步路径查找
        const start = data.start;
        const end = data.end;
        
        // 直线路径作为回退
        const path = [start, end];
        
        return { path, tankId: data.tankId };
    }

    fallbackAnalyzePlayerBehavior(data) {
        const patterns = {
            aggressive: 0.5,
            defensive: 0.5,
            mobile: 0.5,
            camping: 0.5
        };
        
        return { patterns, tankId: data.tankId };
    }

    fallbackCalculateOptimalStrategy(data) {
        const strategy = 'balanced';
        return { strategy, tankId: data.tankId };
    }

    // 初始化网格（所有Worker）
    async initAllGrids(width, height, buildings) {
        const promises = this.workers
            .filter(w => w.worker)
            .map(w => {
                return new Promise((resolve) => {
                    const taskId = ++this.taskId;
                    this.pendingTasks.set(taskId, { resolve, reject: resolve });
                    
                    w.worker.postMessage({
                        type: 'initGrid',
                        id: taskId,
                        data: { width, height, buildings }
                    });
                });
            });
        
        await Promise.all(promises);
        console.log('✅ 所有AI Worker网格初始化完成');
    }

    // 清理资源
    destroy() {
        this.workers.forEach(w => {
            if (w.worker) {
                w.worker.terminate();
            }
        });
        this.workers = [];
        this.pendingTasks.clear();
        this.taskQueue = [];
    }
}

// 导出单例
window.AIWorkManager = AIWorkManager; 